package com.acooly.module.openapi.client.api.transport;

import com.acooly.core.utils.net.HttpResult;
import com.acooly.core.utils.net.Https;
import com.acooly.module.openapi.client.api.exception.ApiClientNetworkException;
import com.acooly.module.openapi.client.api.exception.ApiClientSocketTimeoutException;
import com.acooly.module.openapi.client.api.exception.ApiServerException;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketTimeoutException;
import java.util.Map;

/**
 * 通讯组件
 * <p>
 * 自动根据请求的schema判断是http还是https（采用全部信任服务端方式）
 *
 * @author zhangpu
 */
public class HttpTransport implements Transport {

	protected static Logger logger = LoggerFactory.getLogger(HttpTransport.class);
	private String gateway;
	private String readTimeout = "30000";
	private String connTimeout = "10000";
	private String contentType = "application/x-www-form-urlencoded";
	private String charset = "utf-8";

	@Override
	public HttpResult request(String message) {
		return request(message, this.gateway);
	}

	@Override
	public HttpResult request(String message, String url, Map<String, String> headers) {
		try {
			HttpResult result = getHttps().post(url, message, headers, false,
					ContentType.create(this.contentType, this.charset));
			if (!String.valueOf(result.getStatus()).startsWith("2")) {
				throw new ApiServerException("status:" + result.getStatus() + ", body:" + result.getBody());
			}
			return result;
		} catch (ApiServerException ase) {
			throw ase;
		} catch (Exception e) {
			if (e.getCause() != null && e.getCause() instanceof SocketTimeoutException) {
				throw new ApiClientSocketTimeoutException("等待响应超时:" + e.getMessage());
			}
			throw new ApiClientNetworkException("通讯错误：" + e.getMessage());
		}
	}

	@Override
	public HttpResult request(String message, String url) {
		return request(message, url, null);
	}

	@Override
	public String exchange(String message) {
		return exchange(message, gateway);
	}

	@Override
	public String exchange(String message, String url) {
		try {
			return doRequest(message, url);
		} catch (ApiServerException ase) {
			throw ase;
		} catch (Exception e) {
			logger.warn("通讯失败,重试一次...");
			return doRequest(message, url);
		}
	}

	protected String doRequest(String message, String url) {
		return request(message, url).getBody();
	}

	public Https getHttps() {
		return Https.getCustomInstance(connTimeout, readTimeout);
	}

	public void setGateway(String gateway) {
		this.gateway = gateway;
	}

	public void setReadTimeout(String readTimeout) {
		this.readTimeout = readTimeout;
	}

	public void setConnTimeout(String connTimeout) {
		this.connTimeout = connTimeout;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

}
